package com.moneyhelper.upms.biz;

import com.moneyhelper.common.biz.CommonBiz;
import com.moneyhelper.upms.dto.FrontUserInfo;
import com.moneyhelper.upms.entity.SysMenu;
import com.moneyhelper.upms.entity.SysRoleMenu;
import com.moneyhelper.upms.entity.SysUser;
import com.moneyhelper.upms.entity.SysUserRole;
import com.moneyhelper.upms.mapper.SysMenuMapper;
import com.moneyhelper.upms.mapper.SysUserMapper;
import com.moneyhelper.upms.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

/**
 * @author： ygl
 * @date： 2019/06/30
 * @Description：
 */
@Service
public class SysUserBiz extends CommonBiz<SysUserMapper, SysUser> {

	@Autowired
	private SysUserRoleMapper sysUserRoleMapper;

	@Autowired
	private SysMenuMapper sysMenuMapper;

	/**
	 * 通过用户id查询用户角色id集合
	 * @param userId
	 * @return
	 */
	public List<String> getRoleIds(String userId) {
		List<String> roleIds = new ArrayList<>();
		Example example = new Example(SysUserRole.class);
		example.createCriteria().andEqualTo("userId",userId);
		List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectByExample(example);
		for (SysUserRole userRole : sysUserRoles) {
			roleIds.add(userRole.getRoleId());
		}
		return roleIds;
	}

	/**
	 * 更新用户角色
	 * @param userId
	 * @param roleIds
	 */
	public void updateRole(String userId, String[] roleIds) {
		// 删除角色对应的菜单权限
		Example example = new Example(SysUserRole.class);
		example.createCriteria().andEqualTo("userId",userId);
		sysUserRoleMapper.deleteByExample(example);

		if (roleIds != null) {
			for (String roleId : roleIds) {
				SysUserRole userRole = new SysUserRole();
				userRole.setUserId(userId);
				userRole.setRoleId(roleId);
				sysUserRoleMapper.insertSelective(userRole);
			}
		}
	}

	public FrontUserInfo getUserInfoUserId(String userId) {
		FrontUserInfo userInfo = new FrontUserInfo();
		SysUser sysUser = mapper.selectByPrimaryKey(userId);
		if (sysUser != null) {
			userInfo.setUserId(sysUser.getId());
			userInfo.setName(sysUser.getName());
			Boolean isSuperAdmin = sysUser.getIsSuperAdmin();
			// 超管返回所有数据
			if (isSuperAdmin) {
				userInfo.setMenuList(sysMenuMapper.selectAll());

			} else {
				userInfo.setMenuList(sysMenuMapper.getMenuByUserId(userId));
			}
		}
		return userInfo;
	}
}
